package com.yzd.netmonitor.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;

public class SignUtils {

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SignUtils.class);

	public static String sign(TreeMap<String, String> params, String signKey) {

		StringBuilder sb = new StringBuilder();
		Set<Entry<String, String>> set = params.entrySet();
		for (Entry<String, String> e : set) {
			String key = e.getKey();
			String value = e.getValue();
			if (StringUtils.equalsIgnoreCase(key, "enc") || StringUtils.isBlank(value)) {
				continue;
			}
			sb.append(value);
		}
		sb.append(signKey);
		logger.info("signSource:{}", sb.toString());
		String enc = "";
		try {
			String encode = URLEncoder.encode(sb.toString(), "UTF-8");
			logger.info("encodeStr:{}", encode);
			enc = DigestUtils.md5Hex(encode).toLowerCase();
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		}
		return enc;
	}

	public String getParamString(TreeMap<String, String> params) {

		StringBuilder sb = new StringBuilder();
		Set<Entry<String, String>> set = params.entrySet();
		for (Entry<String, String> e : set) {
			String key = e.getKey();
			String value = e.getValue();
			if (StringUtils.isBlank(value)) {
				continue;
			}
			sb.append(key).append("=").append(value).append("&");
		}
		return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
	}

}
